// dashboard.js
const app = getApp()

Page({
  data: {
    chefName: '厨师',
    todayOrders: 0,
    pendingOrders: 0,
    cookingOrders: 0,
    completedOrders: 0,
    recentOrders: []
  },

  onLoad() {
    // 检查登录状态和角色
    if (!app.globalData.isLoggedIn) {
      wx.redirectTo({
        url: '/pages/auth/login/login'
      })
      return
    }
    
    console.log('厨师工作台权限检查:')
    console.log('- 用户信息:', app.globalData.userInfo)
    console.log('- 用户角色:', app.globalData.userInfo?.role)
    console.log('- 全局角色:', app.globalData.userRole)
    console.log('- isChef() 结果:', app.isChef())
    
    if (!app.isChef()) {
      wx.showToast({
        title: '权限不足',
        icon: 'none'
      })
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/index/index'
        })
      }, 1500)
      return
    }
    
    this.loadDashboardData()
  },

  onShow() {
    this.loadDashboardData()
  },

  // 加载仪表板数据
  async loadDashboardData() {
    try {
      // 确保从云数据库加载最新数据
      await app.refreshOrders()
      
      // 获取厨师姓名
      const chefName = app.globalData.userInfo?.nickname || '厨师'
      
      const orders = app.globalData.orders || []
      const today = new Date().toDateString()
      
      // 计算今日订单
      const todayOrders = orders.filter(order => {
        const orderDate = new Date(order.createTime).toDateString()
        return orderDate === today
      }).length

      // 计算各状态订单数量
      const pendingOrders = orders.filter(order => order.status === 'pending').length
      const cookingOrders = orders.filter(order => order.status === 'cooking').length
      const completedOrders = orders.filter(order => order.status === 'completed').length

      // 获取最近5个订单
      const recentOrders = orders.slice(0, 5).map(order => {
        // 预处理订单数据，确保时间格式正确
        const processedOrder = { ...order } // 创建副本，避免修改原数据
        
        // 确保必要字段存在
        if (!processedOrder._id) {
          processedOrder._id = order.id || `temp_${Date.now()}_${Math.random()}`
        }
        
        if (!processedOrder.status) {
          processedOrder.status = 'pending'
        }
        
        if (!processedOrder.items || !Array.isArray(processedOrder.items)) {
          processedOrder.items = []
        }
        
        if (!processedOrder.totalItems) {
          processedOrder.totalItems = processedOrder.items.length || 0
        }
        
        if (processedOrder.createTime) {
          // 如果createTime是Date对象，转换为字符串
          if (processedOrder.createTime instanceof Date) {
            processedOrder.createTime = processedOrder.createTime.toISOString()
          }
          // 如果是字符串，确保格式正确
          else if (typeof processedOrder.createTime === 'string') {
            // 检查是否是有效的日期字符串
            const testDate = new Date(processedOrder.createTime)
            if (isNaN(testDate.getTime())) {
              processedOrder.createTime = new Date().toISOString() // 如果无效，使用当前时间
            }
          }
        } else {
          // 如果没有时间，使用当前时间
          processedOrder.createTime = new Date().toISOString()
        }
        
        return processedOrder
      })

      this.setData({
        chefName,
        todayOrders,
        pendingOrders,
        cookingOrders,
        completedOrders,
        recentOrders
      })
      
      console.log('厨师仪表板数据加载完成:', {
        chefName,
        todayOrders,
        pendingOrders,
        cookingOrders,
        completedOrders,
        recentOrdersCount: recentOrders.length
      })
    } catch (error) {
      console.error('加载厨师仪表板数据失败:', error)
      // 如果云数据库加载失败，使用本地数据
      const orders = app.globalData.orders || []
      const chefName = app.globalData.userInfo?.nickName || '厨师'
      const today = new Date().toDateString()
      
      const todayOrders = orders.filter(order => {
        const orderDate = new Date(order.createTime).toDateString()
        return orderDate === today
      }).length

      const pendingOrders = orders.filter(order => order.status === 'pending').length
      const cookingOrders = orders.filter(order => order.status === 'cooking').length
      const completedOrders = orders.filter(order => order.status === 'completed').length
      const recentOrders = orders.slice(0, 5).map(order => {
        // 预处理订单数据，确保时间格式正确
        const processedOrder = { ...order } // 创建副本，避免修改原数据
        
        // 确保必要字段存在
        if (!processedOrder._id) {
          processedOrder._id = order.id || `temp_${Date.now()}_${Math.random()}`
        }
        
        if (!processedOrder.status) {
          processedOrder.status = 'pending'
        }
        
        if (!processedOrder.items || !Array.isArray(processedOrder.items)) {
          processedOrder.items = []
        }
        
        if (!processedOrder.totalItems) {
          processedOrder.totalItems = processedOrder.items.length || 0
        }
        
        if (processedOrder.createTime) {
          // 如果createTime是Date对象，转换为字符串
          if (processedOrder.createTime instanceof Date) {
            processedOrder.createTime = processedOrder.createTime.toISOString()
          }
          // 如果是字符串，确保格式正确
          else if (typeof processedOrder.createTime === 'string') {
            // 检查是否是有效的日期字符串
            const testDate = new Date(processedOrder.createTime)
            if (isNaN(testDate.getTime())) {
              processedOrder.createTime = new Date().toISOString() // 如果无效，使用当前时间
            }
          }
        } else {
          // 如果没有时间，使用当前时间
          processedOrder.createTime = new Date().toISOString()
        }
        
        return processedOrder
      })

      this.setData({
        chefName,
        todayOrders,
        pendingOrders,
        cookingOrders,
        completedOrders,
        recentOrders
      })
    }
  },

  // 格式化时间显示
  formatTime(timeInput) {
    if (!timeInput) {
      return '时间未知'
    }
    
    try {
      let date
      
      // 如果已经是Date对象，直接使用
      if (timeInput instanceof Date) {
        date = timeInput
      } else {
        // 否则尝试创建Date对象
        date = new Date(timeInput)
      }
      
      if (isNaN(date.getTime())) {
        return String(timeInput)
      }
      
      const now = new Date()
      const diff = now - date
      const oneDay = 24 * 60 * 60 * 1000
      
      let result
      if (diff < oneDay) {
        // 今天
        result = date.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit',
          hour12: false 
        })
      } else if (diff < 2 * oneDay) {
        // 昨天
        result = '昨天 ' + date.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit',
          hour12: false 
        })
      } else {
        // 其他日期
        result = date.toLocaleDateString('zh-CN', { 
          month: '2-digit', 
          day: '2-digit',
          hour: '2-digit', 
          minute: '2-digit',
          hour12: false 
        })
      }
      
      return result
    } catch (error) {
      console.error('时间格式化失败:', error)
      return String(timeInput)
    }
  },



  // 跳转到服务管理
  goToDishManage() {
    wx.navigateTo({ url: '/pages/chef/dishes/dishes' })
  },

  // 跳转到订单管理
  goToOrderManage() {
    wx.navigateTo({ url: '/pages/chef/orders/orders' })
  },

  // 跳转到成员管理
  goToMemberManage() {
    wx.navigateTo({ url: '/pages/chef/members/members' })
  },

  // 跳转到设置页面
  goToSettings() {
    wx.navigateTo({ url: '/pages/chef/settings/settings' })
  },

  // 查看订单详情
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id
    console.log('查看订单详情，orderId:', orderId)
    wx.navigateTo({ 
      url: `/pages/chef/orders/order-detail/order-detail?id=${orderId}` 
    })
  },

  // 接单
  acceptOrder(e) {
    const orderId = e.currentTarget.dataset.id
    console.log('接单操作，orderId:', orderId)
    
    wx.showModal({
      title: '确认接单',
      content: '确定要接受这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateOrderStatus(orderId, 'cooking')
        }
      }
    })
  },

  // 完成订单
  completeOrder(e) {
    const orderId = e.currentTarget.dataset.id
    console.log('完成订单操作，orderId:', orderId)
    
    wx.showModal({
      title: '确认完成',
      content: '确定要标记这个订单为已完成吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateOrderStatus(orderId, 'completed')
        }
      }
    })
  },

  // 更新订单状态
  async updateOrderStatus(orderId, newStatus) {
    try {
      console.log('开始更新订单状态，orderId:', orderId, 'newStatus:', newStatus)
      
      // 验证orderId
      if (!orderId) {
        console.error('订单ID为空，无法更新状态')
        wx.showToast({ title: '订单ID无效', icon: 'error' })
        return
      }
      
      // 先更新本地数据
      const orders = app.globalData.orders
      const orderIndex = orders.findIndex(order => order._id === orderId)
      
      console.log('查找订单结果:', { orderIndex, totalOrders: orders.length, orderId })
      
      if (orderIndex !== -1) {
        orders[orderIndex].status = newStatus
        app.globalData.orders = orders
        
        // 重新加载数据
        this.loadDashboardData()
        
        // 同步更新云数据库
        const { orderService } = require('../../../utils/cloud.js')
        const result = await orderService.updateOrderStatus(orderId, newStatus)
        
        if (result.success) {
          console.log('订单状态已同步到云数据库')
          
          const statusText = {
            'cooking': '已接单',
            'completed': '已完成'
          }[newStatus]
          
          wx.showToast({ title: statusText, icon: 'success' })
          
          // 通知首页刷新订单统计
          if (app.globalData) {
            app.globalData.needRefreshOrderStats = true
          }
        } else {
          console.error('同步订单状态到云数据库失败:', result.error)
          wx.showToast({ title: '状态更新失败', icon: 'error' })
        }
      } else {
        console.error('在本地订单中找不到指定ID的订单:', orderId)
        wx.showToast({ title: '订单不存在', icon: 'error' })
      }
    } catch (error) {
      console.error('更新订单状态失败:', error)
      wx.showToast({ title: '状态更新失败', icon: 'error' })
    }
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '待确认',
      'cooking': '制作中',
      'completed': '已完成',
      'cancelled': '已取消',
      'rejected': '已拒绝'
    }
    return statusMap[status] || status
  },

  // 切换回成员模式
  switchToMember() {
    wx.showModal({
      title: '界面切换',
      content: '确定要切换回用户界面吗？您的厨师身份将保持不变。',
      success: (res) => {
        if (res.confirm) {
          // 不改变用户角色，只是切换界面
          wx.reLaunch({ url: '/pages/index/index' })
        }
      }
    })
  },

  // 页面下拉刷新
  onPullDownRefresh() {
    this.loadDashboardData()
    wx.stopPullDownRefresh()
  },

  // 跳转到家庭活动管理
  goToActivityManage() {
    wx.navigateTo({
      url: '/pages/chef/activities/activities'
    })
  }
}) 